package com.zhang.apipassenger.interceptor;

import com.zhang.internalcommon.constant.CommonStatusEnum;
import com.zhang.internalcommon.dto.ResponseResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

/**
 * 类功能描述
 *
 * @author Kye
 * @date 2025-09-08
 */
@RestControllerAdvice
public class GlobalValidationExceptionHandler {
	@ExceptionHandler(MethodArgumentNotValidException.class)
	public ResponseResult validationExceptionHandler(MethodArgumentNotValidException ex) {
		return ResponseResult.fail(CommonStatusEnum.VALIDATION_EXCEPTION.getCode(), ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());
	}

	@ExceptionHandler(ConstraintViolationException.class)
	public ResponseResult constraintViolationExceptionHandler(ConstraintViolationException ex) {
		Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
		String message = "";
		for (ConstraintViolation<?> c : constraintViolations) {
			message = c.getMessage();
		}
		return ResponseResult.fail(CommonStatusEnum.VALIDATION_EXCEPTION.getCode(), message);
	}
}
